import html2canvas from "html2canvas";
import {momentFormat} from "@/config/common";

export class Dom2ImageHandler {

  constructor() {
  }

  // 截图功能 页面元素转图片
  transform(elemId = '') {
    return new Promise((resolve, reject) => {
      if (!elemId) reject();
      const canvas = document.createElement("canvas");
      const srcElement = document.getElementById(elemId);
      if (!srcElement) reject();
      // 获取父级的宽高
      const computedStyle = window.getComputedStyle(srcElement);
      const width = parseInt(computedStyle.width);
      const height = parseInt(computedStyle.height);
      // 宽高 * 2 并放大 2 倍 是为了防止图片模糊
      canvas.width = width * 2;
      canvas.height = height * 2;
      canvas.style.width = width + 'px';
      canvas.style.height = height + 'px';
      const context = canvas.getContext("2d");
      context.scale(2, 2);
      const options = {
        backgroundColor: null,
        canvas: canvas,
        useCORS: true
      }
      html2canvas(srcElement, options).then((canvas) => {
        // toDataURL 图片格式转成 base64
        const dataURL = canvas.toDataURL("image/png");
        this.downloadImage(dataURL);
        resolve(dataURL);
      })
    });
  }

  //下载图片
  downloadImage(url) {
    // 如果是在网页中可以直接创建一个 a 标签直接下载
    const a = document.createElement('a');
    a.href = url;
    a.download = `截图-${moment().format(momentFormat.timestamp)}`;
    a.click();
    // document.removeChild(a);
  }

}